<?php

namespace app\backend\controller\sys;

use app\common\controller\Basic;
use app\common\service\sys\MenuService;

/**
 * 节点管理
 * @author kaige
 * @update 2022-04-27
 */
class Menu extends Basic
{

  // 初始化
  protected function initialize()
  {
    parent::initialize();
    // 当前控制器服务实例化
    $this->service = new MenuService();
  }

  /**
   * 菜单配置列表
   */
  public function menulist()
  {
    if ($this->request->isGet()) {
      $data = input('param.');
      $result = $this->service->_list($data, false);
      $tree = [];
      if ($result && $result['count'] > 0) {
        $tree = \app\common\util\TreeUtil::list_to_tree($result['data'], 0, 'id', 'pid', 'children');
        \app\common\util\TreeUtil::tree_add_field($tree);
      }
      return json(_layui($result['count'], $tree));
    }
    return _jerr(1000);
  }

  /**
   * 编辑
   */
  public function edit()
  {
    if (request()->isPost()) {
      $data = input('param.');
      url_decode($data);
      return json($this->service->saveMenuData($data));
    }
    if (request()->isGet()) {
      $id = input('id/d', 0);
      $info = $this->service->getInfoById($id);
      if (isset($info['p_menu_id'])) {
        $pd = $this->service->getInfoByWhere([
          ['menu_id', '=', $info['p_menu_id']]
        ]);
        if ($pd) {
          $info['p_menu_id_name'] = $pd['name'];
        }
      }
      return _jok('ok', $info);
    }
    return _jerr(1000);
  }

  /**
   * 查看
   */
  public function look()
  {
    if (request()->isGet()) {
      $id = input('id/d', 0);
      $info = $this->service->getInfoById($id);
      if (isset($info['p_menu_id'])) {
        $pd = $this->service->getInfoByWhere([
          ['menu_id', '=', $info['p_menu_id']]
        ]);
        if ($pd) {
          $info['p_menu_id_name'] = $pd['name'];
        }
      }
      return _jok('ok', $info);
    }
    return _jerr(1000);
  }

  /**
   * 更新字段
   */
  public function updatefield()
  {
    if (request()->isPost()) {
      $id = input('id/d', 0);
      $field = input('field', '');
      $value = input('value', '');
      $node = input('node', '');
      $post = input('param.');
      if (!isset($post['formpage']) || empty($post['formpage'])) { //空，节点获取更新
        $data = [];
        $data['list'] = [];
        // 第一种，初始 节点，啥都没配置，先配置名称
        if ($id === 0 && $field == 'name') {
          $data['list'][] = [
            'node' => $node,
            'name' => $field,
            'value' => $value
          ];
          return json($this->service->saveNode($data));
        } else {
          //第二种，配置节点
          $fieldNotIN = ['id', 'type', 'node', 'createtime', 'updatetime'];
          if (in_array($field, $fieldNotIN)) {
            return _jerr('非法更新');
          }
          if ($field == 'menu_id') {
            // 找重复
            if ($this->service->getInfoByWhere(['menu_id' => $value])) {
              return _jerr('存在重复');
            }
          }
          $minfo = $this->service->getInfoById($id);
          if ($minfo && $field == 'p_menu_id') {
            //当前是修改，就需要判断是否会陷入死循环
            if ($this->service->checkDie($minfo['menu_id'], $value) === false) {
              return _jerr('填错了吧，会陷入死循环的');
            }
          }
          if ($field == 'is_auth' && $value == 1) {
            // 需更新is_login
            $this->service->updateField($id, 'is_login', 1);
          }
          if ($this->service->updateField($id, $field, $value)) {
            return _jok(1021);
          };
        }
      } elseif ($post['formpage'] == 'menulist') { //非空 菜单更新
        // 找重复
        if ($field == 'id') {
          if ($this->service->getInfoByWhere(['menu_id' => $value])) {
            return _jerr('存在重复');
          }
          if ($this->service->updateField($id, 'menu_id', $value)) {
            return _jok(1021);
          };
        } elseif ($field == 'pid') {
          //当前是修改，就需要判断是否会陷入死循环
          $minfo = $this->service->getInfoById($id);
          if ($this->service->checkDie($minfo['menu_id'], $value) === false) {
            return _jerr('填错了吧，会陷入死循环的');
          }
          if ($this->service->updateField($id, 'p_menu_id', $value)) {
            return _jok(1021);
          };
        } elseif ($field == 'sort') {
          if ($this->service->updateField($id, 'sort', $value)) {
            return _jok(1021);
          };
        }
      }
      return _jerr(1022);
    }
    return _jerr(1000);
  }

  /**
   * 获取反常节点
   */
  public function getabnormal()
  {
    if (request()->isGet()) {
      return json($this->service->getabnormal());
    }
    return _jerr(1000);
  }

  /**
   * 显示节点列表
   */
  public function index()
  {
    if (request()->isGet()) {
      return json($this->service->getNodeGroupList());
    }
    return _jerr(1000);
  }

  /**
   * 清理无效的节点记录
   */
  public function clear()
  {
    if (request()->isGet()) {
      return json($this->service->clear());
    }
    return _jerr(1000);
  }

  /**
   * 保存节点变更
   */
  public function savenode()
  {
    if ($this->request->isPost()) {
      $data = $this->request->post();
      return json($this->service->saveNode($data));
    }
    return _jerr(1000);
  }

  /**
   * 获取用户菜单树
   */
  public function getusermenutree()
  {
    if (request()->isGet()) {
      $menu = $this->service->getMenuDataTree($this->user['id']);
      $data = [
        'menus' => $this->get_view_menu($menu['menu']),
        'leftmenu' => $this->get_left_menu($menu['leftmenu'])
      ];
      return _jok('ok', $data);
    }
    return _jerr(1000);
  }

  /**
   * 迎合前端菜单
   */
  protected function get_view_menu($array)
  {
    $str = "[";
    foreach ($array as $vo) {
      $str .= "{'id':'" . (isset($vo['menu_id']) ? $vo['menu_id'] : '') . "'";
      $str .= ",'title':'" . (isset($vo['title']) ? $vo['title'] : '') . "'";
      $str .= ",'pageURL':'" . (isset($vo['url']) ? $vo['url'] : '') . "'";
      $str .= ",'name':'" . (isset($vo['name']) ? $vo['name'] : '') . "'";
      $str .= ",'icon':'" . (isset($vo['icon']) ? $vo['icon'] : '') . "'";
      $str .= ",'openType':'" . (isset($vo['open_type']) ? $vo['open_type'] : '') . "'";
      $str .= ",'width':'" . (isset($vo['width']) ? $vo['width'] : '') . "'";
      $str .= ",'height':'" . (isset($vo['height']) ? $vo['height'] : '') . "'";
      $str .= ",'maxopen':'" . (isset($vo['is_max']) ? $vo['is_max'] : '') . "'";
      $str .= ",'extend':'" . ((isset($vo['is_extend']) && $vo['is_extend'] == 1) ? 'true' : 'false') . "'";
      $getsubm = "";
      if (!empty($vo['children'])) {
        $getsubm = $this->get_view_menu($vo['children']);
      }
      $getsubm = rtrim($getsubm, ',]') . "]";
      if (strlen($getsubm) > 10) {
        $str .= ",'childs':" . $getsubm . "";
      } else {
        $str .= ",'childs':null";
      }
      $str .= "},";
    }
    $str .= "]";
    $str = rtrim($str, ',]') . "]";
    return $str;
  }

  /**
   * 左侧菜单
   */
  protected function get_left_menu($array)
  {
    $str = "[";
    foreach ($array as $vo) {
      $str .= "{'id':'" . (isset($vo['menu_id']) ? $vo['menu_id'] : '') . "'";
      $str .= ",'title':'" . (isset($vo['title']) ? $vo['title'] : '') . "'";
      $str .= ",'pageURL':'" . (isset($vo['node']) ? $vo['node'] : '') . "'";
      $str .= ",'name':'" . (isset($vo['name']) ? $vo['name'] : '') . "'";
      $str .= ",'icon':'" . (isset($vo['icon']) ? $vo['icon'] : '') . "'";
      $str .= ",'openType':'" . (isset($vo['open_type']) ? $vo['open_type'] : '') . "'";
      $str .= ",'width':'" . (isset($vo['width']) ? $vo['width'] : '') . "'";
      $str .= ",'height':'" . (isset($vo['height']) ? $vo['height'] : '') . "'";
      $str .= ",'maxopen':'" . (isset($vo['is_max']) ? $vo['is_max'] : '') . "'";
      $str .= "},";
    }
    $str .= "]";
    $str = rtrim($str, ',]') . "]";
    return $str;
  }

  /**
   * 批量操作 启禁用、保留废弃
   */
  public function checkfun()
  {
    if ($this->request->isPost()) {
      $data = $this->request->post();
      return json($this->service->checkfun($data));
    }
    return _jerr(1000);
  }
}
